package com.yuwei.live


import android.annotation.SuppressLint
import android.graphics.Color
import android.os.CountDownTimer
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.indicator.Indicator
import com.yuwei.base.RoutePath
import com.yuwei.common.adapter.FragmentAdapter
import com.yuwei.common.entity.AddCarEntity
import com.yuwei.common.mvi.BaseMviActivity
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.GoodsEntity
import com.yuwei.image.glide.GlideImageLoader
import com.yuwei.live.adapter.GoodsAdapter
import com.yuwei.live.adapter.MoreLiveAdapter
import com.yuwei.live.databinding.ActivityLiveDetailBinding
import com.yuwei.live.dialog.RedEnvelopeDialog
import com.yuwei.live.entity.*
import com.yuwei.live.view.AllFragment
import com.yuwei.live.view.CommerceRankingFragment
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Duration
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import java.text.SimpleDateFormat
import kotlin.random.Random

/**
 * i视频-01-榜单_带货榜V1.1-20250604
 * i视频-04-抢红包V1.1-20250605
 *
 */
@Route(path = RoutePath.LIVE_DETAIL_ACTIVITY)
class LiveDetailActivity : BaseMviActivity<ActivityLiveDetailBinding, LiveViewModel>() {
    @Autowired
    lateinit var video: LiveEntityItem
    lateinit var countDownTimer: CountDownTimer
    lateinit var fragmentAdapter: FragmentAdapter
    lateinit var exoPlayer: ExoPlayer
    val moreLiveAdapter = MoreLiveAdapter()
    val goodsAdapter = GoodsAdapter()
    var time = 0L
    val list = mutableListOf<BannerEntityItem>()
    lateinit var dkContext: DanmakuContext
    lateinit var danmaku: BaseDanmaku
    var favNum = 911
    override fun successData(it: UiState.onSuccess<*>) {
        when (it.type) {
            "getBannerList" -> {
                list.addAll(it.data as BannerEntity)
            }
            "getRankingList" -> {
                val data = it.data as RankingEntity
                moreLiveAdapter.data.addAll(data)
            }
            "getGoodsList" -> {
                goodsAdapter.data.addAll(it.data as GoodsEntity)
                goodsAdapter.notifyDataSetChanged()
            }
            "getAddCar" -> {
                ToastUtils.showShort("添加成功")
            }
        }
    }

    override fun failureData(error: String) {

    }

    private val tabList = listOf("全 站", "带货榜")

    @SuppressLint("ObjectAnimatorBinding", "ClickableViewAccessibility")
    override fun initView() {
        vm.sendIntent(LiveIntent.getBannerList)
        vm.sendIntent(LiveIntent.getRankingList)
        ARouter.getInstance().inject(this)
        // 1. 初始化 ExoPlayer
        exoPlayer = ExoPlayer.Builder(this).build()
        exoPlayer.repeatMode = Player.REPEAT_MODE_ALL

        // 2. 绑定 PlayerView
        binding.playerView.player = exoPlayer

        // 3. 设置媒体资源（URL 或本地文件）
        val mediaItem = MediaItem.fromUri(video.videopath) // 替换为你的视频URL
        exoPlayer.setMediaItem(mediaItem)
        exoPlayer.prepare()
        exoPlayer.play() // 自动播放
        binding.liveDetailAuthorName.text = video.name
        GlideImageLoader.loadCircleImage(this, binding.liveDetailAuthorIcon, video.avatar_url)
    }

    override fun initData() {
        //退出dialog
        binding.liveDetailClose.setOnClickListener {
            XPopup.Builder(this)
                .autoDismiss(false) // 点击按钮不自动关闭
                .hasShadowBg(true) // 显示半透明背景
                .asCustom(object : BasePopupView(this) {
                    override fun getInnerLayoutId(): Int = R.layout.exit_dialog_layout
                    override fun onCreate() {
                        super.onCreate()
                        findViewById<View>(R.id.exit).setOnClickListener {
                            finish()
                            dismiss()
                        }
                        findViewById<View>(R.id.find).setOnClickListener {
                            ToastUtils.showShort("寻找更多主播")
                        }
                    }

                })
                .show()

        }
        //红包倒计时
        countDownTimer = object : CountDownTimer(10000, 1000) {
            override fun onTick(p0: Long) {
                time = p0
                val simpleDateFormat = SimpleDateFormat("mm:ss")
                val s = simpleDateFormat.format(p0)
                binding.redEnvelopeTime.text = s
            }

            override fun onFinish() {
                binding.redEnvelopeTime.visibility = View.GONE
                binding.redEnvelope.visibility = View.GONE
            }
        }.start()

        // 排行榜
        binding.hourList.setOnClickListener {
            XPopup.Builder(this)
                .enableDrag(true)
                .asCustom(object : BottomPopupView(this) {
                    override fun getImplLayoutId(): Int = R.layout.ranking_layout

                    override fun onCreate() {
                        super.onCreate()
                        val vp2 = findViewById<ViewPager2>(R.id.vp2)
                        val tl = findViewById<TabLayout>(R.id.tl)
                        fragmentAdapter = FragmentAdapter(
                            this@LiveDetailActivity,
                            listOf(AllFragment(), CommerceRankingFragment())
                        )
                        // 确保不会在弹窗的 onCreate 里重复设置 Adapter
                        vp2.adapter = fragmentAdapter
                        TabLayoutMediator(
                            tl, vp2
                        ) { tab, position ->
                            tab.text = tabList[position]
                        }.attach()
                    }
                })
                .show()
        }
        //红包dialog
        binding.redEnvelope.setOnClickListener {
            val dialog = RedEnvelopeDialog(this)
            dialog.setTime(time)
            dialog.show()
        }
        //更多直播
        binding.moreLive.setOnClickListener {
            XPopup.Builder(this)
                .enableDrag(true)
                .popupAnimation(PopupAnimation.TranslateFromRight)
                .asCustom(object : BasePopupView(this) {
                    override fun getInnerLayoutId(): Int = R.layout.more_live_layout

                    override fun onCreate() {
                        super.onCreate()
                        val banner =
                            findViewById<Banner<BannerEntityItem, BannerImageAdapter<BannerEntityItem>>>(
                                R.id.banner
                            )
                        //绑定轮播图适配器
                        banner.setAdapter(object : BannerImageAdapter<BannerEntityItem>(list) {
                            override fun onBindView(
                                holder: BannerImageHolder,
                                data: BannerEntityItem,
                                position: Int,
                                size: Int
                            ) {
                                GlideImageLoader.loadCornerImage(
                                    this@LiveDetailActivity,
                                    holder.imageView,
                                    data.imageUrl,
                                    10
                                )
                            }
                        })
                        //设置指示器
                        banner.indicator = CircleIndicator(this@LiveDetailActivity)
                        banner.isAutoLoop(true)
                        banner.start()
                        //设置更多直播列表
                        val recyclerView = findViewById<RecyclerView>(R.id.more_live_rv)
                        recyclerView.adapter = moreLiveAdapter
                        recyclerView.layoutManager = GridLayoutManager(this@LiveDetailActivity, 2)
                    }
                })
                .show()
        }
        //商品列表
        binding.openGoods.setOnClickListener {
            XPopup.Builder(this)
                .enableDrag(true)
                .asCustom(object : BottomPopupView(this) {
                    override fun getImplLayoutId(): Int {
                        return R.layout.goods_layout
                    }

                    override fun onCreate() {
                        super.onCreate()
                        vm.sendIntent(LiveIntent.getGoodsList)
                        val recyclerView = findViewById<RecyclerView>(R.id.goods_rv)
                        val shopCardTv = findViewById<TextView>(R.id.shop_card_tv)
                        val shopOrderTv = findViewById<TextView>(R.id.order_tv)
                        shopOrderTv.setOnClickListener {
                            ARouter.getInstance().build(RoutePath.MODULE_MINE_ALL_ORDERS_ACTIVITY).navigation()
                        }
                        shopCardTv.setOnClickListener {
                            ARouter.getInstance().build(RoutePath.GOODS_SHOPPING).navigation()
                        }
                        recyclerView.adapter = goodsAdapter
                        recyclerView.layoutManager = LinearLayoutManager(this@LiveDetailActivity)
                        goodsAdapter.addChildClickViewIds(R.id.goods_add_car)
                        goodsAdapter.setOnItemChildClickListener { adapter, view, position ->
                            when (view.id) {
                                R.id.goods_add_car -> {
                                    vm.sendIntent(
                                        LiveIntent.getAddCar(
                                            AddCarEntity(
                                                1,
                                                goodsAdapter.data[position].id
                                            )
                                        )
                                    )
                                }
                            }
                        }
                    }
                })
                .show()

        }
        //购物车详情页面
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build(RoutePath.LIVE_GOODS_DETAIL_ACTIVITY)
                .withSerializable("goods_detail", goodsAdapter.data[position]).navigation()
        }
        //直播间广告
        binding.liveDetailAdvertisement.setOnClickListener {
            XPopup.Builder(this)
                .enableDrag(true)
                .asCustom(object : BottomPopupView(this) {
                    override fun getImplLayoutId(): Int {
                        return R.layout.advertisement_layout
                    }

                    override fun onCreate() {
                        super.onCreate()
                        val view = findViewById<ImageView>(R.id.advertisement_iv)
                        GlideImageLoader.loadResImage(
                            this@LiveDetailActivity,
                            R.drawable.advertisement,
                            view
                        )
                    }
                })
                .show()
        }
        //初始化弹幕
        initBarrage()
        //发送弹幕
        binding.sendBarrage.setOnClickListener {
            NewBeBarrage(binding.commentContent.text.toString())
        }
        binding.klv.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5
        )
        binding.liveDetailFav.setOnClickListener {
            binding.klv.addFavor()
            ++favNum
            binding.liveDetailAuthorLikeNum.text = "${favNum}本场点赞"
        }
    }

    fun initBarrage() {
        dkContext = DanmakuContext.create()
        binding.dv.apply {
            enableDanmakuDrawingCache(false)
            clear()
            removeAllDanmakus(true)
            prepare(object : BaseDanmakuParser() {
                override fun parse(): IDanmakus {
                    return Danmakus()
                }

            }, dkContext)
        }
    }

    var isStarted: Boolean = false
    fun NewBeBarrage(msg: String) {
        if (msg.isNullOrEmpty()) {
            ToastUtils.showShort("发送内容不能为空")
            return
        }
        danmaku = dkContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        danmaku.text = msg
        danmaku.duration = Duration(5000)
        when (Random.nextInt(5)) {
            0 -> danmaku.textColor = Color.RED
            1 -> danmaku.textColor = Color.YELLOW
            2 -> danmaku.textColor = Color.BLUE
            3 -> danmaku.textColor = Color.GREEN
            4 -> danmaku.textColor = Color.BLACK
            5 -> danmaku.textColor = Color.GRAY
        }
        danmaku.textSize = 40f
        danmaku.time = binding.dv.currentTime
        binding.dv.addDanmaku(danmaku)
        if (!isStarted) {
            binding.dv.start()
            isStarted = true
        }
        binding.commentContent.setText("")
    }

    override fun onPause() {
        super.onPause()
        exoPlayer.pause()
    }

    override fun onResume() {
        super.onResume()
        exoPlayer.play()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.dv.release()
        binding.dv.removeAllLiveDanmakus()
        exoPlayer.release()
        countDownTimer.cancel()
    }
}